using Microsoft.EntityFrameworkCore;

namespace Extensions.Configuration.Database
{
    public class ConfigurationDatabaseContext : DbContext
    {
        /// <summary>
        /// 默认键最大长度
        /// </summary>
        private const int DefaultKeyMaxLength = byte.MaxValue;

        /// <summary>
        /// 默认值最大长度
        /// </summary>
        private const int DefaultValueMaxLength = 1024;

        public ConfigurationDatabaseContext(DbContextOptions contextOptions)
            : base(contextOptions)
        {
        }

        /// <summary>
        /// 配置实体
        /// </summary>
        public DbSet<ConfigurationEntity> ConfigurationEntities { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var configurationBuilder = modelBuilder.Entity<ConfigurationEntity>();

            configurationBuilder.HasKey(c => c.Id);
            configurationBuilder.Property(c => c.Id)
                .IsRequired().ValueGeneratedOnAdd();

            configurationBuilder.HasIndex(c => c.Key);
            configurationBuilder.Property(c => c.Key)
                .IsRequired()
                .HasMaxLength(DefaultKeyMaxLength);

            configurationBuilder.Property(c => c.Value)
                .HasMaxLength(DefaultValueMaxLength);
            
            // OPTIMIZE:设置更新时间为每次更新(包含新增)时自动更新；创建时间为每次新增时自动更新
        }
    }
}